import Vue from 'vue'
import Router from 'vue-router'
import routes from './staticRoute'
import store from './store'

Vue.use(Router)

const route = new Router({
  routes
})
var flag = true

route.beforeEach(async (to, from, next) => {
  console.log(to);
  let a = await store.state.router
  if (a.length != 0 && flag) {
    a.forEach(item => {
      item.component = getComponent(item.name)
      if(item.children){
       item.children = getChildren(item.children)
      }
      route.addRoute(item)
    })
    flag = false
    next({
      ...to,
      replace:true
    })
  } else {
    next()
  }
  function getComponent(path) {
    return () => import(`@/views/${path}`)
  }
  function getChildren(children){
    children.forEach(item=>{
      item.component = getComponent(item.name)
      if(item.children!=undefined){
        getChildren(item.children)
      }
    })
    return children
  }
})
export default route






































// export default new Router({
//   mode: 'history',
//   base: process.env.BASE_URL,
//   routes: [
//     {
//       path: '/',
//       redirect:'/index'
//     },
//     {
//       path: '/index',
//       name: 'Index',
//       component: () => import('./views/Index.vue'),
//       redirect:'/home',
//       children:[
//         {
//           path: '/home',
//           name: 'Home',
//           component: () => import('./views/Home.vue')
//         },
//         {
//           path: '/cate',
//           name: 'Cate',
//           component: () => import('./views/Cate.vue')
//         },
//         {
//           path: '/cart',
//           name: 'Cart',
//           component: () => import('./views/Cart.vue')
//         },
//         {
//           path: '/my',
//           name: 'My',
//           component: () => import('./views/My.vue')
//         }
//       ]
//     },
//     {
//       path: '/login',
//       name: 'Login',
//       component: () => import('./views/Login.vue')
//     },
//     {
//       path: '/about',
//       name: 'About',
//       component: () => import('./views/About.vue')
//     }
//   ]
// })
